<script setup>
import { cloneDeep } from 'lodash-es';
import Fuse from 'fuse.js';
import { useRequest, useWatch } from '@/hooks';
import { useSelectIns } from '@/store/zdwh.js';
import { useFileUpload } from '../hooks.js';
import { TableList } from '@/components/MainComponents.js';
import { saveDeviceSys } from '@/api/index.js';
import { Message, MessageBox } from 'element-ui';

const emit = defineEmits(['success']);
const visible = ref(false);
const selectInsStore = useSelectIns();
const [
  uploadFile,
  fileList,
  fileObj,
  uploadFileUrl,
  headers,
  handleBeforeUpload,
  handleUploadError,
  handleExceed,
  handleUploadSuccess,
] = useFileUpload('/energyservice/device/system/import', ['xls', 'xlsx', 'xlsm']);
const searchValue = ref(null);
let fuse;
const searchData = query => {
  const results = fuse.search(query);
  return results.map(result => result.item);
};
const tableData = ref([]);
const columnObj = ref({
  index: true,
  columnData: [
    { text: true, prop: 'dsViewId', label: '设备系统编号' },
    { text: true, prop: 'dsName', label: '设备系统名称' },
    { text: true, prop: 'sortNum', label: '同级别排序号' },
    { text: true, prop: 'superViewId', label: '上级设备系统编号' },
    { text: true, prop: 'superName', label: '上级设备系统名称' },
  ],
});

const querySearch = () => {
  if (!searchValue.value || searchValue.value?.length < 1) {
    tableData.value = cloneDeep(fileObj.value?.importEnDeviceSystemTemplateList) ?? [];
  } else {
    fuse = new Fuse(fileObj.value?.importEnDeviceSystemTemplateList ?? [], {
      keys: ['dsViewId', 'dsName'],
      threshold: 0.4,
    });
    tableData.value = searchData(searchValue.value);
  }
};
const cancel = () => {
  fileList.value = [];
  searchValue.value = null;
  tableData.value = [];
  visible.value = false;
};
const handleSave = () => {
  if (fileList.value.length < 1) {
    Message.error('请上传文件');
  } else {
    MessageBox.confirm(fileObj.value.repetitiveMessage || '请确认信息无误', '提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }).then(() => {
      runSave({ key: fileObj.value.key });
    });
  }
};
const changeRowStyle = ({ row }) => {
  if (row?.updateFlag === '1') {
    return 'repeatRow';
  }
};

const [, , runSave] = useRequest(saveDeviceSys, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      Message.success(res.msg);
      cancel();
      emit('success', true);
    }
  },
});

useWatch(
  fileObj,
  n => {
    tableData.value = cloneDeep(n?.importEnDeviceSystemTemplateList) ?? [];
    searchValue.value = null;
  },
  { deep: true },
);
defineExpose({ visible });
</script>

<template>
  <el-dialog :visible.sync="visible" width="70%" :before-close="cancel" append-to-body>
    <div slot="title" class="dialog-title">
      <span class="tit">
        <span class="u-prim-text">导入设备系统表</span>
      </span>
    </div>
    <div class="u-prim-text u-fs16">{{ selectInsStore.selectIns?.enterpriseName ?? '' }}</div>
    <el-upload
      ref="uploadFile"
      :file-list="fileList"
      :action="uploadFileUrl"
      :data="{ enterpriseCode: selectInsStore.selectIns?.enterpriseCode }"
      :headers="headers"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :limit="1"
      accept=".xls,.xlsx,.xlsm"
      name="multiFile"
      class="upload-demo u-mt20"
    >
      <el-button size="small" plain class="el-icon-upload2" type="primary" style="font-size: 14px">
        点击上传文件
      </el-button>
      <span slot="tip" class="el-upload__tip u-ml10 u-text">格式：xls .xlsx .xlsm</span>
    </el-upload>
    <div class="u-mt20 u-mb20">
      <el-input
        v-filter-input
        style="width: 200px; margin-right: 10px"
        v-model.trim="searchValue"
        placeholder="请输入设备系统ID/名称"
        size="small"
        clearable
      />
      <el-button icon="el-icon-search" type="primary" size="small" @click="querySearch">查询</el-button>
    </div>
    <TableList
      :total="0"
      :height="400"
      :tableData="tableData"
      :columObj="columnObj"
      :row-class-name="changeRowStyle"
    ></TableList>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" plain @click="cancel">取 消</el-button>
      <el-button type="primary" size="small" @click="handleSave">保 存</el-button>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
